<template>
  <div class="page-container">
    <div class="car-purchase-box">
      <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="listSearcherChange" />
      <table-index
        :selectedKeys="selectedRows.rowKeys"
        :table="table"
        @loadData="loadData"
        @select="select"
        @selectAll="selectAll"
        @selectionChange="selectionChange"
      >
        <template #carLicenseNo="{ record }">
          <div class="link" @click="onLink(record)">
            <p>{{ record.carLicenseNo }}</p>
            <p>{{ record.carModelName }}</p>
          </div>
        </template>
      </table-index>
    </div>
  </div>
  <!-- 结算 -->
  <confirmCost ref="confirmCostRef" @confirm="confirmSuccess" />
  <!-- 修改费用 -->
  <modifyCost ref="modifyCostRef" @confirm="loadData" />
  <!-- 导入 -->
  <import-modal
    ref="imoportRef"
    action="/carAssetFee/importCarAssetFeeSettlementExcel"
    download-import="/购置费结算导入模版.xlsx"
    @ok="loadData"
  />
</template>

<script setup lang="ts" name="CarPurchaseList">
  import { reactive, onMounted, computed, ref, nextTick } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { purchaseFeeListV5, exportPurchaseFee } from '@/api/asset/car'
  import { getWayByAccount } from '@/api/finance/turnover'
  import { checkToConfirm, checkManyToConfirm } from '@/api/finance/carPurchase'
  import useNavigate from '@/hooks/useNavigate'
  import confirmCost from '@/views/assets/car/car-manage/confirm-cost.vue'
  import modifyCost from '@/views/assets/car/car-manage/modify-cost.vue'
  import { useExport } from '@/hooks/list'
  import { usePageDict } from '@/hooks/useDict'
  import { Message } from '@arco-design/web-vue'
  import { evalQueryParam } from '@/utils'
  import { useRoute } from 'vue-router'
  import dayjs from 'dayjs'

  const route = useRoute()
  const routeQuery = route.query

  const dict = usePageDict('carAssetFeeDict')
  const { navigateTo } = useNavigate()
  const imoportRef = ref<any>()

  const searchList = computed(() => {
    return [
      {
        label: '车牌号',
        prop: 'carIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_carLicensenno_bySite',
          params: {
            // 取所有状态的车，包含已处置和已归还的
            operateStatusList: [10, 20, 30, 40, 50, 60],
          },
        },
      },
      { label: '归属门店', prop: 'siteIdList', type: 'remote-select', attrs: { multiple: true, type: 'multiple_site_listBystaff' } },
      { label: '费用状态', prop: 'feeStatuses', type: 'a-select', multiple: true, options: dict.carAssetFeeEnum },
      {
        label: '应结日期',
        prop: 'dueRange',
        type: 'i-range-picker',
        change: (value: string[] = []) => {
          queryParam.dueStartDate = value[0]
          queryParam.dueEndDate = value[1]
        },
      },
      { label: '结算人', prop: 'userIdList', type: 'remote-select', attrs: { multiple: true, type: 'store_staff_useId_multiple' } },
      {
        label: '收支方式',
        prop: 'payTypeList',
        type: 'a-select',
        options: wayByAccountList,
        attrs: {
          multiple: true,
        },
      },
      {
        label: '完成结算日期',
        prop: 'payRange',
        type: 'i-range-picker',
        change: (value: string[]) => {
          // 前端补充时分秒
          queryParam.payTimeStart = value[0] ? value[0] + ' 00:00:00' : value[0]
          queryParam.payTimeEnd = value[1] ? value[1] + ' 23:59:59' : value[1]
        },
      },
      { label: '费用名称', prop: 'feeNameIdList', type: 'a-select', multiple: true, options: dict.carPurchaseEnum },
      { label: '期数', prop: 'payableNumStr', type: 'a-input', placeholder: '请输入，如第1期' },
      { label: '运营状态', prop: 'operateStatusList', type: 'a-select', multiple: true, options: dict.feeOperateStatusEnum },
    ]
  })

  // 修改费用
  const modifyCostRef = ref()
  const table = useTable({
    columns: [
      { title: '车辆信息', dataIndex: 'carLicenseNo', slotName: 'carLicenseNo', width: 160 },
      { title: '归属门店', dataIndex: 'siteName' },
      {
        title: '费用名称',
        dataIndex: 'feeName',
        width: 150,
        render: (record: any) => {
          if (record.installment == 1) {
            return `${record.feeCategoryName}-${record.feeName}`
          } else {
            return record.feeName
          }
        },
      },
      { title: '结算金额', dataIndex: 'totalAmount', unit: '元' },
      { title: '应结日期', dataIndex: 'dueDate', width: 120 },
      { title: '费用状态', dataIndex: 'feeStatusName' },
      { title: '完成结算时间', dataIndex: 'payTime', width: 180 },
      { title: '结算人', dataIndex: 'confirmUserName' },
      { title: '收支方式', dataIndex: 'payTypeName' },
      { title: '费用备注', dataIndex: 'remark', ellipsis: true },
      { title: '结算备注', dataIndex: 'settlementRemark', ellipsis: true },
    ],
    operates: [
      {
        label: '结算',
        show: (record: any) => record.feeStatus === 0 || record.feeStatus === 3 || record.feeStatus === 5,
        permission: 'svms:finance:reconciliation:car-purchase.confirm',
        method: (record: any) => {
          console.log('confirm')
          hanldeConfirm(record)
        },
      },
      {
        label: '修改费用',
        show: (record: any) => record.feeStatus === 0 || record.feeStatus === 3 || record.feeStatus === 5,
        permission: 'svms:finance:reconciliation:car-purchase.edit',
        method: (record: any) => {
          modifyCostRef.value.open({
            // 如果是购置费补充费 传入的是 id，否则传入的是 businesId
            id: record.feeCategory == 5 ? record.id : record.businesId,
            businesId: record.businesId,
            carId: record.carId,
            feeNameId: record.feeNameId,
            feeCategory: record.feeCategory,
            installment: record.installment,
            businesCode: record.businesCode,
            title: `修改费用-${record.carLicenseNo}`,
          })
        },
      },
    ],
    buttons: [
      {
        mode: 'import',
        label: '导出',
        permission: 'svms:finance:reconciliation:car-purchase.export',
        method: () => handleExport(),
      },
      {
        mode: 'import',
        label: '导入结算',
        permission: 'svms:finance:reconciliation:car-purchase.import',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        mode: 'import',
        label: '批量结算',
        type: 'primary',
        permission: 'svms:finance:reconciliation:car-purchase.batchConfirm',
        method: () => {
          handleBatchConfirm()
        },
      },
    ],
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      showChecked: (record: any) => {
        // 已付款、已收款不支持
        return [0, 3, 5].includes(record.feeStatus)
      },
    },
  })
  const handleExport = () => {
    useExport(exportPurchaseFee, queryParam)
  }
  // 结算弹窗
  const confirmCostRef = ref<any>()
  // 结算操作辅助，用于结算成功后清除选中项
  const confirmOperateHelper = {
    operate: '', // single || batch
    id: null, // 结算单id
  }
  // 单个结算
  const hanldeConfirm = (record: any) => {
    const param = [
      {
        businesId: record.businesId,
        idList: [record.id],
        installmentList: [record.payableNum],
      },
    ]
    // 设置结算操作辅助
    confirmOperateHelper.operate = 'single'
    confirmOperateHelper.id = record.id
    // 校验是否可以结算
    checkToConfirm(param).then((res: any) => {
      if (res.code === 200) {
        if (res.result) {
          // 打开弹窗
          confirmCostRef.value.open({
            idList: param[0].idList,
            supplierType: record.supplierType,
            supplierName: record.supplierName,
            title: `结算-${record.carLicenseNo}`,
          })
        }
      }
    })
  }
  // 批量结算
  const handleBatchConfirm = () => {
    const rowKeys = selectedRows.rowKeys
    if (rowKeys && rowKeys.length > 0) {
      // 设置结算操作辅助
      confirmOperateHelper.operate = 'batch'
      // 将选中的数据进行分组
      const tempGroup: any = {}
      for (var k in selectedRows) {
        let val = selectedRows[k]
        if (val && val.id && rowKeys.includes(val.id)) {
          const { id, businesId, payableNum } = val
          if (tempGroup[businesId]) {
            tempGroup[businesId].idList.push(id)
            tempGroup[businesId].installmentList.push(payableNum)
          } else {
            tempGroup[businesId] = {
              businesId,
              idList: [id],
              installmentList: [payableNum],
            }
          }
        }
      }
      // tempGroup 转换为数组
      const param = Object.values(tempGroup)
      checkManyToConfirm(param).then((res: any) => {
        if (res.code === 200) {
          if (res.result) {
            const firstRowKey = rowKeys[0]
            const firstRecord = selectedRows[firstRowKey]
            // 打开弹窗
            confirmCostRef.value.open({
              idList: rowKeys,
              supplierType: firstRecord.supplierType,
              supplierName: firstRecord.supplierName,
              title: `批量结算`,
            })
          }
        }
      })
    } else {
      Message.warning('请选择需要结算的数据')
    }
  }

  /**
   * 收支方式
   */
  const wayByAccountList = ref([])
  const getwayByAccountList = () => {
    getWayByAccount({}).then((res) => {
      wayByAccountList.value = res.result.map((item) => {
        return {
          label: item.name,
          value: item.value,
        }
      })
    })
  }
  // 点击详情
  const onLink = (record: { carId: any; carLicenseNo: any }) => {
    navigateTo(`/car-manage/detail/${record.carId}?from=car-manage`, `${record.carLicenseNo}-车辆详情`)
  }
  // 清空选择的内容
  const clearSelected = () => {
    selectedRows.rowKeys = []
    for (var k in selectedRows) {
      if (k !== 'rowKeys') {
        delete selectedRows[k]
      }
    }
  }
  // 查询条件触发查询列表
  const listSearcherChange = (page: number) => {
    clearSelected()
    loadData()
  }
  // 结算成功
  const confirmSuccess = () => {
    loadData()
    // 清空选中数据-批量
    if (confirmOperateHelper.operate == 'batch') {
      clearSelected()
    } else if (confirmOperateHelper.operate == 'single') {
      // 清空选中数据-单个
      if (confirmOperateHelper.id) {
        delete selectedRows[confirmOperateHelper.id]
        selectedRows.rowKeys = selectedRows.rowKeys.filter((key: any) => key !== confirmOperateHelper.id)
      }
    }
  }
  const queryParam = reactive<any>({
    payRange: [],
  })
  // 列表接口调用
  const loadData = () => {
    const fn = useFetchTableDataApi(table, queryParam, purchaseFeeListV5)
    fn().then((result) => {
      table.dataList = result.data.map((item) => {
        //去掉时分秒
        return Object.assign(item, { dueDate: dayjs(item.dueDate).format('YYYY-MM-DD') })
      })
    })
  }
  // 选中的数据
  const selectedRows = reactive<any>({
    rowKeys: [],
  })
  const select = (rowKeys: number[], rowKey: number, record: any) => {
    let isSelect = rowKeys.length > 0 && rowKeys.includes(rowKey)
    if (isSelect) {
      selectedRows[rowKey] = {
        id: record.id,
        businesId: record.businesId,
        payableNum: record.payableNum,
        supplierType: record.supplierType,
        supplierName: record.supplierName,
      }
    } else {
      delete selectedRows[rowKey]
    }
  }
  const selectAll = () => {
    nextTick(() => {
      // 更新选中数据
      table.dataList.forEach((item: any) => {
        if (selectedRows.rowKeys.includes(item.id)) {
          selectedRows[item.id] = {
            id: item.id,
            businesId: item.businesId,
            payableNum: item.payableNum,
            supplierType: item.supplierType,
            supplierName: item.supplierName,
          }
        } else {
          delete selectedRows[item.id]
        }
      })
    })
  }
  const selectionChange = (rowKeys: number[]) => {
    selectedRows.rowKeys = rowKeys
  }

  onMounted(() => {
    // 时间
    if (routeQuery.startTime && routeQuery.endTime) {
      queryParam.dueRange = [routeQuery.startTime, routeQuery.endTime]
      queryParam.dueStartDate = routeQuery.startTime
      queryParam.dueEndDate = routeQuery.endTime
    }
    // 费用状态
    if (routeQuery.feeStatuses) {
      let feeStatuses = evalQueryParam(routeQuery.feeStatuses)
      queryParam.feeStatuses = feeStatuses
    }
    // 费用名称
    if (routeQuery.feeNameIdList) {
      let feeNameIdList = evalQueryParam(routeQuery.feeNameIdList)
      queryParam.feeNameIdList = feeNameIdList
    }
    // 运营状态
    if (routeQuery.operateStatusList) {
      let operateStatusList = evalQueryParam(routeQuery.operateStatusList)
      queryParam.operateStatusList = operateStatusList
    }
    loadData()
    // 查询条件收支方式
    getwayByAccountList()
  })
</script>

<style lang="less" scoped>
  .content-item {
    .content-item-name {
      margin-bottom: 4px;
      .staff-can-click {
        color: rgb(var(--primary-6));
        cursor: pointer;
      }
      .tag-pickup {
        padding: 0 3px;
        line-height: 18px;
      }
      :deep(.custom-tag) {
        margin-right: 6px;
        position: relative;
        top: 1px;
      }
    }
    .content-item-tag :deep(.custom-tag.default) {
      line-height: 20px;
      padding: 4px 8px;
    }
  }
  .content-item + .content-item {
    margin-top: 10px;
  }
  .link {
    display: flex;
    flex-direction: column;
    padding: 1px 4px;
    color: rgb(var(--link-6));
    font-size: 14px;
    line-height: 1.5715;
    text-decoration: none;
    background-color: transparent;
    border-radius: var(--border-radius-small);
    cursor: pointer;
  }
</style>
